package com.sz.hiling.commons;

import com.auth0.jwt.interfaces.Claim;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;


@Component
public class JwtUtils {
    private static String key = "zhiling";
    //规定时间范围
    private static long validateTime = 3600000;

    public static String createJwt(String id,String subject, String roles) {
        //设置发布时间
        long  startTime = System.currentTimeMillis();
        Date stime = new Date(startTime);
        //过期时间
        Date expire = new Date(validateTime + startTime);
        //得到jwtBuilder的对象
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(id)
                .setIssuedAt(stime)
                .setSubject(subject)//设置发布编码时间
                .setExpiration(expire)//设置过期时间
                .signWith(SignatureAlgorithm.HS256,key)//使用hs256进行编码
                .claim("roles", roles);//将转入的参数进行编码
        //返回编码对象
        return jwtBuilder.compact();
    }
    //解析token
    public static Claims parseToken(String e){
        Claims claims=Jwts
                .parser()
                .setSigningKey(key)
                .parseClaimsJws(e)//解析传入的token
                .getBody();
        return claims;
    }

    public static void main(String[] args) {
        String delete = createJwt("1","删除功能","delete");
        System.out.println(delete);
        //Claims claim= parseToken(createJwt("1","删除功能","delete"));
    }
}
